package com.github.wings27.interview.Math;

import static org.junit.Assert.assertEquals;

/**
 * Created with IntelliJ IDEA.
 * Project Name: common-interview-problems
 * Date Created: 2013/10/28 下午8:16
 *
 * @author wings
 */
public class BigIntAddition {
    public static void main(String[] args) {
        String a = "499509283453";
        String b = "091237042345";
        assertEquals((long) (Long.valueOf(a) + Long.valueOf(b)), (long) Long.valueOf(add(a, b)));
    }

    public static String add(String a, String b) {
        StringBuilder builder1 = new StringBuilder(a);
        StringBuilder builder2 = new StringBuilder(b);
        int longerLength = Math.max(builder1.length(), builder2.length());
        StringBuilder result = new StringBuilder(longerLength + 1);
        builder1 = builder1.reverse();
        builder2 = builder2.reverse();
        int carriage = 0;
        for (int i = 0; i < longerLength; i++) {
            int cur = (i < builder1.length() ? builder1.charAt(i) - '0' : 0) +
                    (i < builder2.length() ? builder2.charAt(i) - '0' : 0) +
                    carriage;
            if (cur > 9) {
                result.append(cur - 10);
                carriage = 1;
            } else {
                result.append(cur);
                carriage = 0;
            }
        }
        return result.reverse().toString();
    }
}
